package Utility;

import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream.GetField;

import Messages.Message;

public class ProposalIDGenerator {
	FileUtilities fileUtilities;

	/**
	 * Generates the proposal id for server. 
	 * @param serverId
	 */
	public  int generateProposalID(String filePath, int incrementor,Message message, int serverId){
		int proposalId = getProposalNumber(filePath,message, serverId);
		return proposalId ;
	}
	
	/**
	 * Get proposal number by parsing the given file
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	public int getProposalNumber(String filePath,Message message, int serverId){
		// The content will be in format N,V
		String fileContent = null;
		try {
			File f = new File(filePath);
			if(!f.exists()){
				System.out.println("I dont have a file. Creating a new file..");
				f.createNewFile();
				int baseProposalNumber = serverId + Constants.PROPOSAL_ID_INCREMENTOR;
				fileContent = baseProposalNumber + ","+ message.getLockValue();
				FileUtilities.writeToFile(filePath, fileContent,false);
			}			
			fileContent = fileUtilities.readFileAsString(filePath);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String[] proposalAndLockValue = fileContent.split(",");
		System.out.println("The proposal ID : " + proposalAndLockValue[0] +" and lock value : " + proposalAndLockValue[1]);
		return Integer.parseInt(proposalAndLockValue[0]);
	}
	
}
